package rush.rushcampus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import rush.rushcampus.common.BaseContext;
import rush.rushcampus.common.Result;
import rush.rushcampus.dto.CommentPageDto;
import rush.rushcampus.entity.Comment;
import rush.rushcampus.entity.User;
import rush.rushcampus.vo.*;
import rush.rushcampus.entity.Article;
import rush.rushcampus.mapper.ArticleMapper;
import rush.rushcampus.mapper.ArticleTagMapper;
import rush.rushcampus.service.IArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import rush.rushcampus.service.ICommentService;
import rush.rushcampus.dto.ArticleDto;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author rush
 * @since 2024-06-11
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {

    @Autowired
    private ArticleTagMapper articleTagMapper;
    @Autowired
    private ICommentService commentService;
    @Autowired
    private CommentServiceImpl commentServiceImpl;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public List<ArticleVo> convertToDto(List<Article> records) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article article : records) {
            ArticleVo articleVo = new ArticleVo();
            BeanUtils.copyProperties(article, articleVo);
            //获取标签集合
//            List<String> ArticleIds = Arrays.asList(article.getTagId().substring(1, article.getTagId().length() - 1).split(","));
            List<Long> ArticleIds = Arrays.stream(article.getTagId().split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            articleVo.setTagsList(articleTagMapper.selectBatchIds(ArticleIds));
            //获取评论数
            articleVo.setCommentCount(commentService.countComment(article.getId(), 0));
            //获取作者部分信息
            User user = userService.getById(article.getCreateUser());
            UserPartInfoVo userPartInfoVo = new UserPartInfoVo();
            userPartInfoVo.setCreateUserName(user.getNickname());
            userPartInfoVo.setCreateUserAvatar(user.getAvatar());
            userPartInfoVo.setCreateUserSex(user.getGender());
            articleVo.setUserPartInfoVo(userPartInfoVo);
            articleVoList.add(articleVo);

        }
        return articleVoList;
    }

    @Override
    public void addArticle(ArticleDto articleDto) {
        Article article = new Article();
        BeanUtils.copyProperties(articleDto, article);
        //标签
        article.setTagId(articleDto.getTags());
        article.setLoveNumber(0L);
        article.setStarNumber(0L);
        article.setView(0L);
        article.setStatus(1);
        log.info("当前用户id:{}", BaseContext.getCurrenId());
        save(article);

    }

    @Override
    public Result updateArticle(ArticleDto articleDto) {
        Article article = new Article();
        BeanUtils.copyProperties(articleDto, article);
        //标签
        article.setTagId(articleDto.getTags());
        boolean b = updateById(article);
        if (!b) {
            return Result.error("修改失败:文章不存在");
        }
        return Result.success("修改成功");
    }

    @Override
    public void removeArticle(Long id, Integer commentType) {
        //1.删除评论
        commentServiceImpl.deleteCommentAndChildren(id, commentType);
        //2.删除文章
        removeById(id);
    }

    @Override
    public Page<ArticleVo> pageList(int page, int pageSize, String title, Integer status, String star) {
        Page<Article> pageInfo = new Page<>(page, pageSize);
        Page<ArticleVo> articleDtoPage = new Page<>();
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(title != null, "title", title);
        if (star != null) {
            //将star转化为List<Long>
            List<Long> starList = Arrays.stream(star.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            queryWrapper.in("id", starList);
        }
        queryWrapper.orderByDesc("update_time");
        this.page(pageInfo, queryWrapper);
        BeanUtils.copyProperties(pageInfo, articleDtoPage, "records");
        articleDtoPage.setTotal(pageInfo.getTotal());
        List<ArticleVo> articleVoList = this.convertToDto(pageInfo.getRecords());
        articleDtoPage.setRecords(articleVoList);
        return articleDtoPage;
    }
    @Transactional
    @Override
    public ArticleInfoVo getArticleById(Long id) {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.eq("id", id);
        Article article = getOne(queryWrapper);
        articleMapper.incrementArticleViewById(id);
        User user = userService.getById(article.getCreateUser());
        UserPartInfoVo userPartInfoVo = new UserPartInfoVo();
        userPartInfoVo.setCreateUserName(user.getNickname());
        userPartInfoVo.setCreateUserAvatar(user.getAvatar());
        userPartInfoVo.setCreateUserSex(user.getGender());
        ArticleInfoVo articleInfoVo = new ArticleInfoVo();
        articleInfoVo.setUserPartInfoVo(userPartInfoVo);
        articleInfoVo.setCreateTime(article.getCreateTime());
        articleInfoVo.setView(article.getView());
        articleInfoVo.setLoveNumber(article.getLoveNumber());
        articleInfoVo.setStarNumber(article.getStarNumber());
        articleInfoVo.setCommentNumber(commentService.countComment(id, 0));
        articleInfoVo.setContent(article.getTitle());
        articleInfoVo.setImgList(article.getImage());
        //查询评论，赋值
//        List<ArticleCommentVo> articleCommentVoList = commentService.listComment(id, 0, 1, 10);
        List<ArticleCommentVo> articleCommentVoList = commentService.listArticleComment(id , 0);
        articleInfoVo.setArticleCommentVoList(articleCommentVoList);
        return articleInfoVo;
    }

    public void starArticle(Long id, Integer isStar) {
        Article article = getById(id);
        if (isStar == 1) {
            article.setStarNumber(article.getStarNumber() + 1);
        } else {
            article.setStarNumber(article.getStarNumber() - 1);
        }
        updateById(article);
    }
}
